package service

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"note.zhiwangyunchuang.com/common"
	"note.zhiwangyunchuang.com/model"
	"note.zhiwangyunchuang.com/utils"
)

func UserLogin(userReq model.User) (bool, string, string) {
	userExists, userInfo := getUserInfoByMobile(userReq.Mobile)
	if !userExists {
		return false, "账号不存在", ""
	}
	err := bcrypt.CompareHashAndPassword([]byte(userInfo.Password), []byte(userReq.Password))
	if err != nil {
		return false, "密码不正确", ""
	}
	token, err := common.ReleaseToken(userInfo)
	if err != nil {
		return false, err.Error(), ""
	}
	return true, "", token
}

func UserRegister(userReq model.User) (bool, string, string) {
	Db := common.GetDb()
	userExists, userInfo := getUserInfoByMobile(userReq.Mobile)
	if userExists {
		return false, "手机号已经被使用，请重试", ""
	}
	enPassword, enErr := bcrypt.GenerateFromPassword([]byte(userReq.Password), bcrypt.DefaultCost)
	if enErr != nil {
		return false, "密码加密错误", ""
	}
	if len(userReq.NickName) == 0 {
		userReq.NickName = utils.RandomString(10)
	}
	// 创建用户信息
	newUser := model.User{
		Model:    gorm.Model{},
		Password: string(enPassword),
		Mobile:   userReq.Mobile,
		NickName: userReq.NickName,
	}
	token, err := common.ReleaseToken(userInfo)
	if err != nil {
		return false, err.Error(), ""
	}
	Db.Create(&newUser)
	return true, "", token
}

func getUserInfoByMobile(mobile string) (bool, model.User) {
	var user model.User
	Db := common.GetDb()
	Db.First(&user, "mobile = ?", mobile)
	if user.ID == 0 {
		return false, user
	}
	return true, user
}
